<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/8/10
 * Time: 12:02
 */

namespace p5\objects;



/**
 * 互斥锁
 * Class RelevantLock
 * @package App\Utilsh
 */
class RelevantLock
{
    var $sem_id;
    var $key;
    var $max_acquire;

    public function __construct($key, $max_acquire = 1)
    {
        $this->key = $key;
        $this->max_acquire = $max_acquire;
    }

    public function init()
    {
        if (!$this->support_semaphore()) {
            return;
        }
        $this->sem_id = sem_get($this->key, $this->max_acquire, 0666, 1);
    }

    public function aquire()
    {
        $this->init();
        if (!$this->support_semaphore()) {
            // 不支持信号量控制
            //TODO  采用文件控制
            return true;
        }
        return sem_acquire($this->sem_id);
    }


    public function release($remove_semaphore = true)
    {
        if (!$this->support_semaphore()) {
            // 不支持信号量控制
            //TODO  采用文件控制
            return true;
        }
        $result = sem_release($this->sem_id);
        if ($remove_semaphore) {
            $result = sem_remove($this->sem_id);
        }
        return $result;
    }

    public function support_semaphore()
    {
        return function_exists("sem_get");
    }

    public function is_linux()
    {
        $os = strtolower(PHP_OS);
        return strpos($os, "linux") > 0;
    }


}